Get Form Data

  • 1. Files

    Option 1. using useState()

    1. create form
    
                  <form>
                    Email: <input type="text"  />
                    Password:  <input type="text"   />
                </form>
                
    2. add useState for form fields
    
                import  {  useState } from 'react';
    
                ..... 
                ....... 
    
                const [email, setEmail] = useState('');
                const [password, setPassword] = useState('');
    
               
    3. apply onchange event in the input field
    
               <form>
                    Email: <input type="text" onChange={ (e) => setEmail(e.target.value)} />
                    Password:  <input type="text"  onChange={ (e) => setPassword(e.target.value)} />
                </form>
    
    4. add onSubmit() to form
    
    <form onSubmit={onSubmit}>
                    Email: <input type="text" onChange={ (e) => setEmail(e.target.value)} />
                    Password:  <input type="text"  onChange={ (e) => setPassword(e.target.value)} />
                    <button type="submit">Submit</button>
    </form>
    
    
    5. define function 'onSubmit'
    
    async function onSubmit(event: FormEvent<HTMLFormElement>) {
    
       event.preventDefault()
    
     
       const response = await fetch('/api/submit', {
            method: 'POST',
            body: JSON.stringify({
              email,password
            }),
       })
    
    
    }
    
    Complete code
    
    import React from 'react';
    import type { ReactElement } from 'react';
    import  {  useState } from 'react';
    import { useRouter } from 'next/router';
    import { FormEvent } from 'react'
    
    
    //  Import the reading layout
    import ReadingLayout from '@/components/ReadingLayout';
    
    function read() {
    
       
    
      const [email, setEmail] = useState('');
      const [password, setPassword] = useState('');
    
    
      async function onSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault()
      
       
         const response = await fetch('/api/submit', {
              method: 'POST',
              body: JSON.stringify({
                email,password
              }),
         })
      
      
      }
    
      
    
        return ( <article className="format dark:format-invert mt-16 mx-auto">
            <br /><br />
                <form onSubmit={onSubmit}>
                    Email: <input type="text" onChange={ (e) => setEmail(e.target.value)} />
                    Password:  <input type="text"  onChange={ (e) => setPassword(e.target.value)} />
                      <button type="submit">Submit</button>
                </form>
    
                </article>
    
        );
    }
    
    export default read;
    
    read.getLayout = function getLayout(page: ReactElement) {
        return (
            <ReadingLayout>
                {page}
            </ReadingLayout>
        )
    }
    
    

    Option 2: using FormData

    1. create form and add name property to the input fields

    2. in the onSubmit() use new FormData()

    
    import Image from 'next/image';
    import { Inter } from 'next/font/google';
    import { FormEvent } from 'react'
    
    export default function Home() {
    
     async function onSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault()
    
       const formData = new FormData(event.currentTarget)
           const response = await fetch('/api/submit', {
            method: 'POST',
            body: formData,
          })
    
        // Handle response if necessary
        const data = await response.json()
        // ...
     }
    return (
     <form onSubmit={onSubmit}>
     <input type="text" name="name" />
     <button type="submit">Submit</button>
     </form>
     );
    }
    
  • 2. Advanced: useState for array
    
    
                    // components/MyForm.js
    
    import { useState } from 'react';
    
    const MyForm = () => {
      const [formData, setFormData] = useState({
        name: '',
        email: '',
        message: ''
      });
    
      const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
          ...prevData,
          [name]: value
        }));
      };
    
      const handleSubmit = (e) => {
        e.preventDefault();
        // Handle form submission here
        console.log('Form submitted:', formData);
        // You can add logic here to send the form data to a server, etc.
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <div>
            <label>
              Name:
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
              />
            </label>
          </div>
          <div>
            <label>
              Email:
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
              />
            </label>
          </div>
          <div>
            <label>
              Message:
              <textarea
                name="message"
                value={formData.message}
                onChange={handleChange}
              ></textarea>
            </label>
          </div>
          <div>
            <button type="submit">Submit</button>
          </div>
        </form>
      );
    };
    
    export default MyForm;